package com.px.user.service;


import com.px.user.entity.RedPackGrab;
import com.px.user.entity.User;
import com.px.user.mapper.RedPackMapper;
import com.px.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class ScheduleTask {

    @Value("${px.random-pack.rp-expire}")
    private String rpExpire;

    @Value("${px.random-pack.rp-user}")
    private String rpUser;

    @Value("${px.random-pack.rp-list}")
    private String rpList;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedPackMapper redPackMapper;

    /**
     * 清理超时未领取红包
     */
    @Scheduled(cron = "${px.schedule.clearRp:-}")
    public void clearRp() {
        log.info("clear red pack");

        Set<String> overdue = redisTemplate.opsForZSet().rangeByScore(rpExpire, 0, System.currentTimeMillis() / 1000);
        if (overdue == null)
            return;

        overdue.forEach(s -> {
            String[] ur = String.valueOf(s).split("-");
            if (ur.length < 2)
                return;
            String rp = rpList + ur[1];
            List<String> moneyList = redisTemplate.opsForList().range(rp, 0, -1);
            if (moneyList == null || moneyList.isEmpty()) {
                redisTemplate.delete(rp);
                redisTemplate.delete(rpUser + ur[1]);
                redisTemplate.opsForZSet().remove(rpExpire, s);
                return;
            }
            double balance = moneyList.stream().mapToDouble(Double::parseDouble).sum();
            redPackMapper.insertGrab(RedPackGrab.builder()
                    .redPackId(Long.valueOf(ur[1]))
                    .toUserId(Long.valueOf(ur[0]))
                    .money(BigDecimal.valueOf(balance)).build());
            userMapper.addMoney(User.builder().id(Long.valueOf(ur[0])).money(BigDecimal.valueOf(balance)).build());
            redisTemplate.delete(rp);
            redisTemplate.delete(rpUser + ur[1]);
            redisTemplate.opsForZSet().remove(rpExpire, s);
        });
    }
}
